package com.sunsharing.transport.file;

import com.sunsharing.common.Constant;
import com.sunsharing.common.URL;
import com.sunsharing.common.anno.Factory;
import com.sunsharing.common.config.Config;
import com.sunsharing.transport.Channel;
import com.sunsharing.transport.Client;
import com.sunsharing.transport.ConnectClients;
import com.sunsharing.transport.IoHandle;
import com.sunsharing.transport.mina.MinaChannel;
import org.apache.log4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-30
 * Time: 下午3:39
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="FILE")
public class FileClient implements Client {
    Logger logger = Logger.getLogger(FileClient.class);
    @Override
    public Channel connect(URL url, IoHandle handler) {
        url.putPar(Constant.URL_PAR_ISCLIENT,"true");
        url.putPar(Constant.URL_PAR_BYCLIENT,"false");
        url.putPar(Constant.URL_PAR_FROM_NODE_ID, Config.getInstance().getNodeId());
        url.putPar(Constant.URL_PAR_ROOT_FILE_PATH, Config.getInstance().getNodeModelByNodeId(Config.getInstance().getNodeId()).rootpath);
        FileChannel client = (FileChannel)ConnectClients.seachClient(Constant.PROTOCOL_FILE, url.getFromNodeId(), url.getToNodeId());

        if(client!=null && !client.isclose())
        {
            logger.warn(client.url+"已经连接过了，不需要再连接了,当前状态:"+client.isclose());
            return client;
        }

        FileChannel fileChannel = new FileChannel(url,null);
        ConnectClients.addClient(fileChannel);
        return fileChannel;
    }

    @Override
    public void close() {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
